package com.sizu.web;


import com.alipay.api.AlipayApiException;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.sizu.common.vo.ResultEntity;
import com.sizu.service.AlibabaPayService;
import com.zhaoyuxi.entity.Orders;
import com.zhaoyuxi.qrcode.service.AlibabapayQrCodeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/statistical/alibaba/pay")
@Slf4j
public class AlibabaPayController {

    @Autowired
    AlibabapayQrCodeService alibabapayQrCodeService;

    @Autowired
    AlibabaPayService alibabaPayService;

    @Autowired
    RedisTemplate<String, String> redisTemplate;

    @RequestMapping("/createPayOrder")
    public ResultEntity createPayOrder(Orders orders) throws AlipayApiException {
        String str="";
        str=orders.getOrderNo();
        str=str.replace("JH", "99");
        str=str.replace("TH","88");
        str=str.replace("XS","77");
        str=str.replace("XT","66");
        log.info("创建支付宝扫码订单开始订单号为:{}", str);
        if (redisTemplate.hasKey(str)) {
            String qrcode = redisTemplate.opsForValue().get(str);
            log.info("根据orderNo:{}到redis 中查询二维码:{}", str, qrcode);
            return ResultEntity.ok("创建支付宝扫码支付订单成功", qrcode);
        }
        log.info("根据orderNo:{}到redis 中查询二维码不存在开始调用支付宝的接口创建预支付订单......");

        Map<String, String> map = new HashMap<>();
        map.put("out_trade_no", str);
        map.put("trade_no", str);
        map.put("total_amount", orders.getTotalAmount());
        map.put("subject", orders.getSubject());
        //商家id
        map.put("store_id", "2088102180157612");
        map.put("timeout_express", "7200m");
        AlipayTradePrecreateResponse qrCodePayOrder = alibabapayQrCodeService.createQrCodePayOrder(map);
        String qrcode = alibabaPayService.getAlibabaPayQRCode(qrCodePayOrder);
        log.info("创建支付宝扫码订单结束订单号为:{}", str);
        return ResultEntity.ok("创建支付宝扫码支付订单成功", qrcode);
    }

}
